package com.v1.video.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.iss.view.common.ToastAlone;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.domain.CommonResultEntity;
import com.v1.video.domain.GuideRecommandEntity;
import com.v1.video.domain.GuideRecommandInfo;
import com.v1.video.httpApi.V1VideoHttpApi;
import com.v1.video.httpmanager.ParamList;
import com.v1.video.httpmanager.ParamList.Parameter;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.util.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * 第4张首次进入时的推荐
 * 
 * @author fengtao
 * 
 */
public class GuideRecommandActivity extends BaseActivity{

	private final String TAG = "GuideRecommandActivity";
	private int index;
	private GridView gridView;
	private LinearLayout layoutGo;
	GuideRecommandAdapter mAdapter;
	private List<GuideRecommandInfo> mLstData = new ArrayList<GuideRecommandInfo>();
	private boolean isNoData = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_guide_recommand);
		Logger.i(TAG, "GuideRecommandActivity 的 Oncreate执行了");
	}
	
	protected void initView() {
		gridView = (GridView) findViewById(R.id.guide_grid_select_fenlei);
		layoutGo = (LinearLayout) findViewById(R.id.guide_lay_btn_back);
		mAdapter = new GuideRecommandAdapter(GuideRecommandActivity.this);
		gridView.setAdapter(mAdapter);
	}

	protected void initData() {
		Logger.i(TAG, "initDate执行了");
//		Helper helper = new Helper();
//		if(!helper.checkConnection(getActivity(), 0)){
//			goToHomePage(getActivity());
//		}else{
			count = 0;
//			if(mLstData == null || mLstData.size() <= 0){
				getServerData();
//			}else{
//				for(int i = 0; i < mLstData.size();i++){
//					mLstData.get(i).isSelect = 0;
//				}
//				mAdapter.setLstData(mLstData);
//				mAdapter.notifyDataSetChanged();
//			}
//		}
	}
	
	private void getServerData(){
		String url = V1VideoHttpApi.GET_RECOMMAND_OF_GUIDE()+"&devid="+Constant.DEVICEID;
    	Logger.i(TAG, "启动推荐Url ="+url);
		RequestManager.getInstance().getRequest(GuideRecommandActivity.this, url, null, GuideRecommandEntity.class, 0, "GuideRecommandFragment", new OnResponseListener(){

			@Override
			public void onSuccess(Object object, int code, String message,String key) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "onSuccess.object="+object.toString());
				
				if(object != null){
					GuideRecommandEntity entity = (GuideRecommandEntity)object;
					com.v1.video.domain.BaseEntity.Header header = entity.getHeader();
					if(header == null){
						ToastAlone.showToast(GuideRecommandActivity.this, "未知错误", Toast.LENGTH_SHORT);
						isNoData = true;
						return;
					}else if(!header.getStatus().equals("1")){
						ToastAlone.showToast(GuideRecommandActivity.this, header.getMessage(), Toast.LENGTH_SHORT);
						isNoData = true;
						return;
					}else if(header.getStatus().equals("1")){
						if(entity.getBody() != null){
							if(entity.getBody().getData() != null){
								
								if(mLstData != null){
									mLstData.clear();
									mLstData.addAll(entity.getBody().getData());
								}else{
									mLstData = entity.getBody().getData();
								}
																
								mAdapter.setLstData(mLstData);
								mAdapter.notifyDataSetChanged();
							}else{
								isNoData = true;
							}
						}else{
//							toast(header.getMessage());
							isNoData = true;
						}
					}else{
						isNoData = true;
					}
				}
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub
				Logger.i(TAG, message);
				isNoData = true;
			}
		});
	}

	protected void setListener() {
		layoutGo.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(count >= 3){
					goToHomePage(GuideRecommandActivity.this);
				}else{
					if(isNoData && mLstData.size() <= 0){
						goToHomePage(GuideRecommandActivity.this);
					}
				}
			}
		});
	}

	private void goToHomePage(Context context) {
		SharedPreferences sp = context.getSharedPreferences(Constant.APP_INFO, context.MODE_PRIVATE);
	    Editor editor = sp.edit();
	    editor.putBoolean("first_start", false);
	    editor.commit();
		// startActivity(new Intent(context,HomepageActivity.class));
		startActivity(new Intent(context, MainPageNewActivity.class));
		
		getTheScidToServer();
		GuideRecommandActivity.this.finish();
	}
	private void getTheScidToServer(){
		StringBuffer buffer = new StringBuffer();
		for(int i = 0; i < mLstData.size();i++){
			GuideRecommandInfo info = mLstData.get(i);
			if(info.isSelect == 1){
				buffer.append(info.getCid());
				buffer.append("|");
				buffer.append(info.getScid());
				if(i != mLstData.size()-1)
				buffer.append(",");
			}
		}
		String strData = buffer.toString();
		Logger.i(TAG, "strData回传id=="+strData);
		goUptoServer(strData);
	}
	
	private void goUptoServer(String data){
		String url = V1VideoHttpApi.GET_RECOMMAND_DATA_TO_SERVER()+"&devid="+Constant.DEVICEID;
    	Logger.i(TAG, "回传cidUrl ="+url);
    	ParamList list = new ParamList();
    	list.add(new Parameter("ids", data));
		RequestManager.getInstance().postRequest(GuideRecommandActivity.this, url, list, CommonResultEntity.class, 0, "GuideRecommandFragment", new OnResponseListener(){

			@Override
			public void onSuccess(Object object, int code, String message,String key) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "onSuccess.object="+object.toString());
				
				if(object != null){
					CommonResultEntity entity = (CommonResultEntity)object;
					com.v1.video.domain.BaseEntity.Header header = entity.getHeader();
					if(header == null){
						ToastAlone.showToast(GuideRecommandActivity.this, "未知错误", Toast.LENGTH_SHORT);
						return;
					}else if(!header.getStatus().equals("1")){
						ToastAlone.showToast(GuideRecommandActivity.this, header.getMessage(), Toast.LENGTH_SHORT);
						return;
					}else if(header.getStatus().equals("1")){
						if(entity.getBody() != null){							
						}else{
//							toast(header.getMessage());
						}
					}
				}
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub
				Logger.i(TAG, message);
				
			}
		});
	}
	public int count = 0;
	public class GuideRecommandAdapter extends BaseAdapter {

		private final String TAG = "GuideRecommandAdapter";
		private LayoutInflater mLayoutInflater;
		private List<GuideRecommandInfo> mLstData;
		

		public GuideRecommandAdapter(Context context) {
			mLayoutInflater = LayoutInflater.from(context);
			mLstData = new ArrayList<GuideRecommandInfo>();
		}

		public List<GuideRecommandInfo> getLstData() {
			return mLstData;
		}

		public void setLstData(List<GuideRecommandInfo> mLstData) {
			if (mLstData != null && mLstData.size() > 0) {
				this.mLstData = mLstData;
				this.notifyDataSetChanged();
			}
		}

		public void setAddLstData(List<GuideRecommandInfo> mLstData) {
			if (mLstData != null && mLstData.size() > 0) {
				this.mLstData.addAll(mLstData);
				this.notifyDataSetChanged();
			}
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mLstData.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mLstData.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final Holder holder;
			if (convertView == null) {
				convertView = mLayoutInflater.inflate(
						R.layout.item_guide_remommand, null);
				holder = new Holder();
				holder.imageBack = (ImageView) convertView
						.findViewById(R.id.item_guide_back);
				holder.imgShow = (ImageView) convertView
						.findViewById(R.id.item_guide_img);
				holder.imgSelect = (ImageView) convertView
						.findViewById(R.id.item_guide_select);
				holder.txtName = (TextView) convertView
						.findViewById(R.id.item_guide_name);
				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}
			if(count < 3){
				layoutGo.setVisibility(View.GONE);
			}else{
				layoutGo.setVisibility(View.VISIBLE);
			}
			final GuideRecommandInfo info = mLstData.get(position);
			holder.txtName.setText(info.getName());
			ImageLoader.getInstance().displayImage(info.getPic(),holder.imgShow, Constant.GUIDE_SHOW_IMG, null);
			holder.imgShow.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(info.isSelect == 0){
						count++;
						info.isSelect = 1;
						holder.imgSelect.setVisibility(View.VISIBLE);
						holder.imageBack.setImageResource(R.drawable.head_bg_side_selected);
						holder.txtName.setTextColor(getResources().getColor(R.color.color_text_selected));
					}else{
						count--;
						info.isSelect = 0;
						holder.imgSelect.setVisibility(View.GONE);
						holder.imageBack.setImageResource(R.drawable.head_bg_side);
						holder.txtName.setTextColor(getResources().getColor(R.color.white));
					}
				}
			});
			return convertView;
		}

		private class Holder {
			public ImageView imageBack;
			public ImageView imgShow;
			public ImageView imgSelect;
			public TextView txtName;
		}

	}
}
